package douyin

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpc"
)

type DouYinConf struct {
	AppId  string
	Secret string
}
type DouYinClient struct {
	conf *DouYinConf
}

func NewDouYinClient(conf *DouYinConf) *DouYinClient {
	return &DouYinClient{
		conf: conf,
	}
}

type AccessTokenReq struct {
	AppId     string `json:"appid"`
	Secret    string `json:"secret"`
	GrantType string `json:"grant_type"`
}

type AccessTokenResp struct {
	ErrNo   int    `json:"err_no"`
	ErrTips string `json:"err_tips"`
	Data    struct {
		AccessToken string `json:"access_token"`
		ExpiresIn   int    `json:"expires_in"`
		ExpiresAt   int    `json:"expiresAt"`
	} `json:"data"`
}

func (c *DouYinClient) GetAccessToken() string {
	req := &AccessTokenReq{
		AppId:     c.conf.AppId,
		Secret:    c.conf.Secret,
		GrantType: "client_credential",
	}
	do, err := httpc.Do(context.Background(), "POST", Code2SessionURL, req)

	//resp, err := tools.Post(Code2SessionURL, req)
	if err != nil {
		logx.Errorf("err:%+v", err)
		return ""
	}
	//resp, err := tools.Post(AccessTokenUrl, req)
	//if err != nil {
	//	logx.Errorf("err:%+v", err)
	//	return ""
	//}
	var data AccessTokenResp
	//io.Copy(os.Stdout, do.Body)
	err = httpc.ParseJsonBody(do, &data)

	//all, err := io.ReadAll(resp.Body)
	//err = json.Unmarshal(all, &data)
	if err != nil {
		logx.Errorf("err:%+v", err)
		return ""
	}
	return data.Data.AccessToken
}
